const config = require("./config")
const { code } = require("./utils/result")
//app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo: function (cb) {
    let that = this
    if(this.globalData.userInfo == null){
       let unionId = wx.getStorageSync('unionId')
       //得到unionId
       if(unionId == null || unionId == ''){
          wx.login({
            success(res){
              wx.request({
                url: config.host + 'users/code2Session' + "?code=" + res.code,
                method: 'GET',
                success(res){
                  if(res.data.code == code.FAILED){
                    wx.showToast({
                      title: '出现错误',
                      icon: 'error'
                    })
                  }
                  else{
                    wx.setStorage('unionId',res.data.data)
                    unionId = wx.getStorageSync('unionId')
                    //如果无法取得unionId转到注册界面
                    if(unionId == null || unionId == ''){
                      wx.redirectTo({
                        url: '/pages/login/login',
                      })
                    }
                    //可以取得unionId,初始化userInfo
                    that.initUserInfo(cb,unionId);
                  }
                }
              })
            },
          })
       }
       //可以取得unionId,初始化userInfo
      else{
        that.initUserInfo(cb,unionId)
      }
    }
    else{
      cb(this.globalData.userInfo)
    }
    
  },
  globalData: {
    userInfo: null
  },
  initUserInfo(cb,unionId){
    var that = this
      wx.request({
        url: config.host +'users/queryUnionId',
        method:'POST',
        data:{
          unionId : unionId
        },
        success(res){
          if(res.data.code == code.SUCCESS){
            that.globalData.userInfo = res.data.data
          }
          cb(that.globalData.userInfo)

        },
      })
  }
})
//appid:wx30d51acdaf80ae67
          //secret:303c9fc92554beee2aff193e2322d025
          //grant_type:authorization_code